import React, { Component } from 'react';
import { Table, Pagination, Message, Dialog, Button, Balloon, Grid } from '@alifd/next';
import IceContainer from '@icedesign/container';
import moment from 'moment';
import TableFilter from './TableFilter';
import EditForm from '../EditForm';
import { ApiOfExpressionPage } from '#/utils/policyApiDefine'
import SearchTableWrapper from '#/hoc/SearchTableWrapper'

const { Row, Col } = Grid;
@SearchTableWrapper(ApiOfExpressionPage)
export default class SearchTable extends Component {
  static displayName = 'SearchTable';

  static propTypes = {};

  static defaultProps = {};

  constructor() {
    super();
    this.state = {
      rowSelection: {
        detailDialogVisible: false,
        onChange: this.onRowSelectChange.bind(this),
        selectedRows: [],
      },
    };
  }
  renderTime = time => {
    return (
      <div>{moment(time).format('YYYY-MM-DD HH:mm:ss')}</div>
    );
  }
  onOpenDetailDialog = (item) => {
    this.setState({
      detailDialogVisible: true,
      editInstance: item ? item : {}
    });
  }
  onCloseDetailDialog = reason => {
    this.setState({
      detailDialogVisible: false
    });
    if (reason == 'success') {
      Message.success('操作成功!');
      this.props.fetch();
    }
  }
  // 选择模式时，选择项改变事件
  onRowSelectChange(ids, records) {
    const { rowSelection } = this.state;
    rowSelection.selectedRowKeys = ids;
    rowSelection.selectedRows = [...rowSelection.selectedRows, ...records];
    this.setState({ rowSelection });
  }

  // 选择模式时，选择好后的确认事件
  onSelectConfirm() {
    let possibleRows = this.state.rowSelection.selectedRows,
      selectedRowKeys = this.state.rowSelection.selectedRowKeys;
    let selectedRows = possibleRows.filter(row => selectedRowKeys.findIndex(key => key == row.id) != -1);
    this.props.onSelect(selectedRows)
  }
  // 渲染操作按钮示例
  renderOper = (value, index, item) => {
    let that = this;
    return (
      <div>
        <Button onClick={() => this.onOpenDetailDialog(item)} type="primary" text>编辑</Button>
      </div>
    );
  }
  render() {
    const { instances } = this.props.bindingData;
    let DisplayTable, ActionBar;
    if (this.props.forSelectUsage === true) {
      DisplayTable = <div>
        <Table
          dataSource={instances.data}
          primaryKey="id"
          loading={this.props.loading}
          hasBorder={false}
          style={{ padding: '0 20px 20px' }}
          onSort={this.props.handleSort}
          rowSelection={this.state.rowSelection}
        >
          <Table.Column width={150} title="表达式类型" dataIndex="type" sortable={true} />
          <Table.Column title="表达式" dataIndex="expressionInfo" />
          <Table.Column width={120} title="连接符" dataIndex="linkSymbol" />
          <Table.Column width={100} title="排序符" dataIndex="sequence" />
        </Table>
      </div>

      ActionBar = <Button onClick={this.onSelectConfirm.bind(this)} type="primary" size="small">选好了</Button>
    }
    else {
      DisplayTable = <div>
        <Table
          dataSource={instances.data}
          loading={this.props.loading}
          hasBorder={false}
          style={{ padding: '0 20px 20px' }}
          onSort={this.props.handleSort}
        >
          <Table.Column width={150} title="表达式类型" dataIndex="type" sortable={true} />
          <Table.Column title="表达式" dataIndex="expressionInfo" />
          <Table.Column width={120} title="连接符" dataIndex="linkSymbol" />
          <Table.Column width={100} title="排序符" dataIndex="sequence" />
          <Table.Column
            width={80}
            title="操作"
            cell={this.renderOper}
          />
        </Table>
      </div>

      ActionBar = <Button onClick={() => this.onOpenDetailDialog()} type="primary" size="small">创建</Button>
    }
    return (
      <IceContainer style={this.props.styles.container}>
        <TableFilter
          filter={this.props.filter}
          forSelectUsage={this.props.forSelectUsage}
          create={this.onOpenDetailDialog.bind(this)}
          onSelect={this.onSelectConfirm.bind(this)}
          match={this.props.match}
        />
        <Row wrap gutter="20" style={styles.formRow}>
          <Col l="8">
            {ActionBar}
          </Col>
          <Col l="16">
            <Pagination
              style={this.props.styles.pagination}
              shape="arrow-only"
              pageSizeSelector="filter"
              current={this.props.page}
              total={instances.pageable.totalElements}
              totalRender={total => `总数: ${total}`}
              pageSize={instances.pageable.size}
              onChange={this.props.handlePaginationChange}
              onPageSizeChange={this.props.handlePageSizeChange}
            />
          </Col>
        </Row>
        {DisplayTable}
        <Pagination
          style={this.props.styles.pagination}
          shape="arrow-only"
          pageSizeSelector="filter"
          current={this.props.page}
          total={instances.pageable.totalElements}
          totalRender={total => `总数: ${total}`}
          pageSize={instances.pageable.size}
          onChange={this.props.handlePaginationChange}
          onPageSizeChange={this.props.handlePageSizeChange}
        />
        <Dialog
          style={{ width: '50%' }}
          title="编制策略表达式信息"
          visible={this.state.detailDialogVisible}
          footer={false}
          onClose={this.onCloseDetailDialog}>
          <EditForm formData={this.state.editInstance} submitCallback={this.onCloseDetailDialog} />
        </Dialog>
      </IceContainer>
    );
  }
}

const styles = {
  formRow: {
    padding: '10px 20px',
  },
  formItem: {
    display: 'flex',
    alignItems: 'center',
    margin: '10px 0',
  },
};
